import java.util.Scanner;
import java.util.ArrayList;
import java.util.List;
import java.io.*;

public class Ticket {
    private String ticketId;
    private Schedule schedule;
    private Seat seat;
    private boolean isSold;

    // 静态列表存储所有票务信息
    private static List<TicketData> ticketDataList = new ArrayList<>();
    private static final String TICKET_FILE = "data/tickets.txt";

    static {
        loadTicketData();
    }

    public Ticket(String ticketId, Schedule schedule, Seat seat) {
        this.ticketId = ticketId;
        this.schedule = schedule;
        this.seat = seat;
        this.isSold = false;
    }

    public String getTicketId() { return ticketId; }
    public Schedule getSchedule() { return schedule; }
    public Seat getSeat() { return seat; }
    public boolean isSold() { return isSold; }
    public void setSold(boolean sold) { isSold = sold; }
    
    // 内部类用于存储票务数据
    private static class TicketData {
        String movieName;
        String timeSlot;
        String hallName;
        int row;
        int col;
        boolean isSold;
        
        TicketData(String movieName, String timeSlot, String hallName, int row, int col, boolean isSold) {
            this.movieName = movieName;
            this.timeSlot = timeSlot;
            this.hallName = hallName;
            this.row = row;
            this.col = col;
            this.isSold = isSold;
        }
    }
    
    // 静态方法：售票
    public static void sellTicket(Scanner scanner) {
        System.out.println("请输入影片名：");
        String movieName = scanner.nextLine();
        System.out.println("请输入场次时间段（如2024-06-01 19:00）：");
        String timeSlot = scanner.nextLine();
        Schedule found = null;
        for (Schedule s : Schedule.getSchedules()) {
            if (s.getMovie().getName().equals(movieName) && s.getTimeSlot().equals(timeSlot)) {
                found = s;
                break;
            }
        }
        if (found == null) {
            System.out.println("未找到该场次。");
            return;
        }
        Hall hall = found.getHall();
        Seat[][] seats = hall.getSeats();
        System.out.println("座位分布（O=空闲，X=已售）：");
        for (int i = 0; i < hall.getRows(); i++) {
            for (int j = 0; j < hall.getSeatsPerRow(); j++) {
                System.out.print(seats[i][j].isOccupied() ? "X " : "O ");
            }
            System.out.println();
        }
        System.out.println("请输入要购买的座位（格式：行 列，例如 3 5）：");
        String[] seatInput = scanner.nextLine().split(" ");
        if (seatInput.length != 2) {
            System.out.println("输入格式有误。");
            return;
        }
        int row, col;
        try {
            row = Integer.parseInt(seatInput[0]) - 1;
            col = Integer.parseInt(seatInput[1]) - 1;
        } catch (NumberFormatException e) {
            System.out.println("输入格式有误。");
            return;
        }
        if (row < 0 || row >= hall.getRows() || col < 0 || col >= hall.getSeatsPerRow()) {
            System.out.println("座位不存在。");
            return;
        }
        if (seats[row][col].isOccupied()) {
            System.out.println("该座位已售出。");
            return;
        }
        seats[row][col].setOccupied(true);
        
        // 保存票务数据
        TicketData ticketData = new TicketData(movieName, timeSlot, hall.getName(), row + 1, col + 1, true);
        ticketDataList.add(ticketData);
        saveTicketData();
        
        System.out.printf("出票成功！影片：%s，场次：%s，座位：%d排%d列，票价：%.2f\n",
            movieName, timeSlot, row + 1, col + 1, found.getPrice());
    }
    
    // 静态方法：退票
    public static void refundTicket(Scanner scanner) {
        System.out.println("请输入影片名：");
        String movieName = scanner.nextLine();
        System.out.println("请输入场次时间段（如2024-06-01 19:00）：");
        String timeSlot = scanner.nextLine();
        Schedule found = null;
        for (Schedule s : Schedule.getSchedules()) {
            if (s.getMovie().getName().equals(movieName) && s.getTimeSlot().equals(timeSlot)) {
                found = s;
                break;
            }
        }
        if (found == null) {
            System.out.println("未找到该场次。");
            return;
        }
        Hall hall = found.getHall();
        Seat[][] seats = hall.getSeats();
        System.out.println("请输入要退票的座位（格式：行 列，例如 3 5）：");
        String[] seatInput = scanner.nextLine().split(" ");
        if (seatInput.length != 2) {
            System.out.println("输入格式有误。");
            return;
        }
        int row, col;
        try {
            row = Integer.parseInt(seatInput[0]) - 1;
            col = Integer.parseInt(seatInput[1]) - 1;
        } catch (NumberFormatException e) {
            System.out.println("输入格式有误。");
            return;
        }
        if (row < 0 || row >= hall.getRows() || col < 0 || col >= hall.getSeatsPerRow()) {
            System.out.println("座位不存在。");
            return;
        }
        if (!seats[row][col].isOccupied()) {
            System.out.println("该座位未售出，无需退票。");
            return;
        }
        seats[row][col].setOccupied(false);
        
        // 更新票务数据
        for (int i = 0; i < ticketDataList.size(); i++) {
            TicketData data = ticketDataList.get(i);
            if (data.movieName.equals(movieName) && data.timeSlot.equals(timeSlot) &&
                data.hallName.equals(hall.getName()) && data.row == row + 1 && data.col == col + 1) {
                ticketDataList.remove(i);
                break;
            }
        }
        saveTicketData();
        
        System.out.printf("退票成功！影片：%s，场次：%s，座位：%d排%d列\n",
            movieName, timeSlot, row + 1, col + 1);
    }
    
    // 静态方法：加载座位状态
    public static void loadSeatStatus() {
        for (TicketData data : ticketDataList) {
            if (data.isSold) {
                // 找到对应的场次和座位
                for (Schedule schedule : Schedule.getSchedules()) {
                    if (schedule.getMovie().getName().equals(data.movieName) &&
                        schedule.getTimeSlot().equals(data.timeSlot) &&
                        schedule.getHall().getName().equals(data.hallName)) {
                        
                        Hall hall = schedule.getHall();
                        Seat[][] seats = hall.getSeats();
                        if (data.row - 1 < hall.getRows() && data.col - 1 < hall.getSeatsPerRow()) {
                            seats[data.row - 1][data.col - 1].setOccupied(true);
                        }
                        break;
                    }
                }
            }
        }
    }
    
    // 文件持久化方法
    private static void saveTicketData() {
        try {
            File dataDir = new File("data");
            if (!dataDir.exists()) {
                dataDir.mkdirs();
            }
            
            FileWriter writer = new FileWriter(TICKET_FILE);
            for (TicketData data : ticketDataList) {
                writer.write(String.format("%s|%s|%s|%d|%d|%s\n",
                    data.movieName, data.timeSlot, data.hallName,
                    data.row, data.col, data.isSold ? "1" : "0"));
            }
            writer.close();
        } catch (IOException e) {
            System.out.println("保存票务数据失败: " + e.getMessage());
        }
    }
    
    private static void loadTicketData() {
        try {
            File file = new File(TICKET_FILE);
            if (!file.exists()) {
                return;
            }
            
            Scanner fileScanner = new Scanner(file);
            while (fileScanner.hasNextLine()) {
                String line = fileScanner.nextLine();
                String[] parts = line.split("\\|");
                if (parts.length >= 6) {
                    String movieName = parts[0];
                    String timeSlot = parts[1];
                    String hallName = parts[2];
                    int row = Integer.parseInt(parts[3]);
                    int col = Integer.parseInt(parts[4]);
                    boolean isSold = parts[5].equals("1");
                    
                    ticketDataList.add(new TicketData(movieName, timeSlot, hallName, row, col, isSold));
                }
            }
            fileScanner.close();
            
            // 加载座位状态
            loadSeatStatus();
        } catch (IOException e) {
            System.out.println("加载票务数据失败: " + e.getMessage());
        }
    }
} 